package cn.alone.order.service.impl;

import cn.alone.basic.constant.BaseConstants;
import cn.alone.basic.service.impl.BaseServiceImpl;
import cn.alone.basic.util.CodeGenerateUtils;
import cn.alone.basic.util.PageList;
import cn.alone.basic.util.QuartzJobInfo;
import cn.alone.order.domain.AdoptOrder;
import cn.alone.order.domain.OrderAddress;
import cn.alone.order.mapper.AdoptOrderMapper;
import cn.alone.order.mapper.OrderAddressMapper;
import cn.alone.order.query.AdoptOrderQuery;
import cn.alone.order.service.IAdoptOrderService;
import cn.alone.org.domain.Employee;
import cn.alone.org.mapper.EmployeeMapper;
import cn.alone.pay.domain.PayBill;
import cn.alone.pay.mapper.PayBillMapper;
import cn.alone.pay.service.IPayBillService;
import cn.alone.pet.domain.Pet;
import cn.alone.pet.mapper.PetMapper;
import cn.alone.product.mapper.ProductMapper;
import cn.alone.product.service.IProductService;
import cn.alone.user.domain.Logininfo;
import cn.alone.user.domain.User;
import cn.alone.user.domain.UserAddress;
import cn.alone.user.mapper.UserAddressMapper;
import cn.alone.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdoptOrderServiceImpl extends BaseServiceImpl<AdoptOrder> implements IAdoptOrderService {
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private AdoptOrderMapper adoptOrderMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PayBillMapper payBillMapper;
    @Autowired
    private IPayBillService payBillService;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private IProductService productService;


    /**
     * 生成领养订单
     * @param params
     * @param currentLogininfo
     * @return
     */
    @Override
    public String submit(Map<String, Object> params, Logininfo currentLogininfo) {
        Long serviceMethod = Long.valueOf(params.get("service_method").toString());
        /*收件地址*/
        Long addressId = Long.valueOf(params.get("address_id").toString());
        Long payMethod = Long.valueOf(params.get("pay_method").toString());
        /*宠物id*/
        Long petId = Long.valueOf(params.get("pet_id").toString());
        /*下架宠物*/
        Pet pet = petMapper.loadById(petId);
        pet.setState(0);
        pet.setOffsaletime(new Date());
        /*给宠物绑定领养人*/
        User user = userMapper.loadByLogininfoId(currentLogininfo.getId());
        pet.setUser_id(user.getId());
        petMapper.update(pet);
        /*生成宠物领养订单*/
        /*保存用户订单地址*/
        UserAddress address = userAddressMapper.loadById(addressId);
        /*赋值*/
        AdoptOrder order = initAdoptOrder(pet, user);
        /*生成唯一支付标识*/
        String paySn = CodeGenerateUtils.generateUnionPaySn();
        order.setPaySn(paySn);
        /*返回自增id*/
        adoptOrderMapper.save(order);
        OrderAddress orderAddress = initOrderAddress(order, address);
        orderAddressMapper.save(orderAddress);
        /*生成支付单并支付*/
        PayBill bill = initPayBill(payMethod, user, order);
        payBillMapper.save(bill);
        QuartzJobInfo jobInfo = new QuartzJobInfo();
        /*定时器名称*/
        jobInfo.setJobName(BaseConstants.PAY_TIMEOUT_CANCEL_ADOPT + order.getId());
        Map<String,Object> map = new HashMap<>();
        map.put("type",BaseConstants.PAY_TIMEOUT_CANCEL_ADOPT);
        map.put("orderId",order.getId());
        /*订单类型和id*/
        jobInfo.setParams(map);
        /*执行时间*/
        jobInfo.setFireDate(order.getLastPayTime());
        return payBillService.pay(bill);

    }

    private PayBill initPayBill(Long payMethod, User user, AdoptOrder order) {
        PayBill bill = new PayBill();
        bill.setDigest("[摘要]领养"+order.getOrderSn()+"支付订单！");
        bill.setMoney(order.getPrice());
        bill.setUnionPaySn(order.getPaySn());
        bill.setLastPayTime(order.getLastPayTime());
        /*0 支付宝 1 微信  2 银联*/
        bill.setPayChannel(payMethod);
        bill.setBusinessType(cn.alone.pay.constants.PayConstants.LINGYANG_ORDER);
        bill.setBusinessKey(order.getId());
        bill.setUser_id(order.getUser_id());
        bill.setShop_id(order.getShop_id());
        /*冗余字段*/
        bill.setNickName(user.getUsername());
        return bill;
    }

    private OrderAddress initOrderAddress(AdoptOrder order, UserAddress address) {
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(address, orderAddress);
        orderAddress.setOrder_id(order.getId());
        orderAddress.setOrderSn(order.getOrderSn());
        return orderAddress;
    }
    private AdoptOrder initAdoptOrder(Pet pet, User user) {
        AdoptOrder order = new AdoptOrder();
        order.setDigest("[摘要]对"+pet.getName()+"领养订单！");
        /*待支付*/
        order.setState(0);
        /*售价*/
        order.setPrice(pet.getSaleprice());
        String orderSn = CodeGenerateUtils.generateOrderSn(user.getId());
        order.setOrderSn(orderSn);
        order.setPet_id(pet.getId());
        order.setUser_id(user.getId());
        order.setShop_id(pet.getShop_id());
        //最后支付时间
        order.setLastPayTime(new Date(System.currentTimeMillis() + 15*60*1000));
        return order;
    }
    @Override
    public PageList<AdoptOrder> admin(AdoptOrderQuery query, Logininfo currentLogininfo) {
        Employee employee = employeeMapper.loadByLogininfoId(currentLogininfo.getId());
        if(employee.getShop_id() != null){
            query.setShopId(employee.getShop_id());
        }
        return super.querpage(query);
    }

    @Override
    public AdoptOrder queryById(Long businessKey) {
        return adoptOrderMapper.queryById(businessKey);
    }

    /**
     * 定时器取消订单
     * @param orderId
     */
    @Override
    public void cancelOrderByQuartz(Long orderId) {
        AdoptOrder order = adoptOrderMapper.queryById(orderId);
        if(order.getState() == 0){
            order.setState(-1);
            adoptOrderMapper.update(order);
            System.out.println("定时任务15分钟后执行取消订单:"+order.getId());
        }

    }

    @Override
    public PageList<AdoptOrder> user(AdoptOrderQuery query, Logininfo currentLogininfo) {
        User user = userMapper.loadByLogininfoId(currentLogininfo.getId());
        query.setUserId(user.getId());
        return super.querpage(query);

    }


}
